import {GeoServer} from "@/utils/geotools";
export function addClapFeature(Cesium,viewer,points,aid = 'identify-area') {
  viewer.entities.removeById(aid);

  let pointsarr = [];
  for(let i = 0;i<points.length;i++){
    let queryPoint = {};
    queryPoint.x = points[i][0];
    queryPoint.y = points[i][1];
    pointsarr[i] = queryPoint;
  }
  let lonLatArr = getLonLatArray(pointsarr);
  viewer.entities.add({
    id: aid,
    name: '单体化标识面',
    polygon: {
      hierarchy: Cesium.Cartesian3.fromDegreesArray(lonLatArr),
      material: new Cesium.Color(0.3, 0.3, 0.0, 0.3),
    },
    classificationType: Cesium.ClassificationType.S3M_TILE // 贴在S3M模型表面
  });
}

export function getLonLatArray(points) {
  var point3D = [];
  points.forEach(function (point) {
    point3D.push(point.x);
    point3D.push(point.y);
  });
  return point3D;
}


// 根据经纬度，获取图层对象。
export function initEarth(eid,Cesium) {
  let viewer = new Cesium.Viewer(eid, {
    baseLayerPicker: false,
    fullscreenButton: false,
    vrButton: false,
    geocoder: false,
    animation: false,
    homeButton: false,
    infoBox: false,
    sceneModePicker: false,
    selectionIndicator: false,
    timeline: false,
    navigationHelpButton: false,
    navigationInstructionsInitiallyVisible: false,
    creditContainer: document.createElement('div'),
    // imageryProvider: new Cesium.MapboxImageryProvider({
    //   mapId: "mapbox.satellite",
    //   accessToken:
    //       "pk.eyJ1IjoibHM4NzAwNjEwMTEiLCJhIjoiY2tqYXZlZ2JrMDI5bTJzcDJmdDNteGhsNyJ9.0wTn4B1ce9Q4U5GnPso5iA",
    // }),
    contextOptions: {
      webgl: {
        alpha: true,
        depth: false,
        stencil: true,
        antialias: true,
        premultipliedAlpha: true,
        preserveDrawingBuffer: true,
        failIfMajorPerformanceCaveat: true,
      },
      allowTextureFilterAnisotropic: true,
    },
    // 天空盒
    skyBox: new Cesium.SkyBox({
      sources: {
        positiveX: require('@/assets/skybox/tycho2t3_80_px.jpg'),
        negativeX: require('@/assets/skybox/tycho2t3_80_mx.jpg'),
        positiveY: require('@/assets/skybox/tycho2t3_80_py.jpg'),
        negativeY: require('@/assets/skybox/tycho2t3_80_my.jpg'),
        positiveZ: require('@/assets/skybox/tycho2t3_80_pz.jpg'),
        negativeZ: require('@/assets/skybox/tycho2t3_80_mz.jpg'),
      },
    }),

  })
  return viewer;
}



// 根据经纬度，获取图层对象。
export function initEarthremoveSensing(eid,Cesium) {
  let viewer = new Cesium.Viewer(eid, {
    baseLayerPicker: false,
    fullscreenButton: false,
    vrButton: false,
    geocoder: false,
    animation: false,
    homeButton: false,
    infoBox: false,
    sceneModePicker: false,
    selectionIndicator: false,
    timeline: false,
    navigationHelpButton: false,
    navigationInstructionsInitiallyVisible: false,
    creditContainer: document.createElement('div'),
    // imageryProvider: new Cesium.MapboxImageryProvider({
    //   mapId: "mapbox.satellite",
    //   accessToken:
    //       "pk.eyJ1IjoibHM4NzAwNjEwMTEiLCJhIjoiY2tqYXZlZ2JrMDI5bTJzcDJmdDNteGhsNyJ9.0wTn4B1ce9Q4U5GnPso5iA",
    // }),

    contextOptions: {
      webgl: {
        alpha: true,
        depth: false,
        stencil: true,
        antialias: true,
        premultipliedAlpha: true,
        preserveDrawingBuffer: true,
        failIfMajorPerformanceCaveat: true,
      },
      allowTextureFilterAnisotropic: true,
    },
    // 天空盒
    skyBox: new Cesium.SkyBox({
      sources: {
        positiveX: require('@/assets/skybox/tycho2t3_80_px.jpg'),
        negativeX: require('@/assets/skybox/tycho2t3_80_mx.jpg'),
        positiveY: require('@/assets/skybox/tycho2t3_80_py.jpg'),
        negativeY: require('@/assets/skybox/tycho2t3_80_my.jpg'),
        positiveZ: require('@/assets/skybox/tycho2t3_80_pz.jpg'),
        negativeZ: require('@/assets/skybox/tycho2t3_80_mz.jpg'),
      },
    }),

  })

  // viewer.scene.sun.show = false; //在Cesium1.6(不确定)之后的版本会显示太阳和月亮，不关闭会影响展示
  // viewer.scene.moon.show = false;
  // viewer.scene.skyBox.show = false;//关闭天空盒，否则会显示天空颜色

  // viewer.scene.undergroundMode = true; //重要，开启地下模式，设置基色透明，这样就看不见黑色地球了

  // viewer.scene.globe.show = false; //不显示地球，这条和地球透明度选一个就可以
  // viewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 0);
  // viewer.scene.backgroundcolor = new Cesium.Color(0, 0, 0, 0);
  // viewer.scene.screenSpaceCameraController.minimumZoomDistance = 50;
  viewer.scene.globe.showGroundAtmosphere = false;
  viewer.scene.globe.baseColor = Cesium.Color.TRANSPARENT;
  viewer.scene.globe.translucency.enabled = true;
  viewer.scene.globe.undergroundColor = undefined;
  viewer.scene.screenSpaceCameraController.minimumZoomDistance = 150;
  // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 1500;
  // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 15000;
  return viewer;
}

// 根据经纬度，获取图层对象。
export function initEarthDefault(eid,Cesium) {
  //三维模型的经纬度（120.832045，32.042819）上部分
  //三维模型下部（120.993580 ，31.958244）下部分

  let viewer = new Cesium.Viewer(eid, {
    baseLayerPicker: false,
    fullscreenButton: false,
    vrButton: false,
    geocoder: false,
    animation: false,
    homeButton: false,
    infoBox: false,
    sceneModePicker: false,
    selectionIndicator: false,
    timeline: false,
    scene3DOnly:true, // 当设置为true时，每个几何图形实例将仅以3D形式呈现，以节省GPU内存
    navigationHelpButton: false,
    navigationInstructionsInitiallyVisible: false,
    creditContainer: document.createElement('div'),

    loadSiblings: true, // 如果为true则不会在已加载完概况房屋后，自动从中心开始超清化房屋
    // cullWithChildrenBounds: true,
    // cullRequestsWhileMoving: true,
    cullRequestsWhileMovingMultiplier: 10, // 值越小能够更快的剔除
    preloadWhenHidden: true,
    preferLeaves: true,
    maximumMemoryUsage: 128, // 内存分配变小有利于倾斜摄影数据回收，提升性能体验
    progressiveResolutionHeightFraction: 0.5, // 数值偏于0能够让初始加载变得模糊
    dynamicScreenSpaceErrorDensity: 0.1, // 数值加大，能让周边加载变快
    dynamicScreenSpaceErrorFactor: 1, // 不知道起了什么作用没，反正放着吧先
    dynamicScreenSpaceError: true, // 根据测试，有了这个后，会在真正的全屏加载完之后才清晰化房屋

    // imageryProvider: new Cesium.MapboxImageryProvider({
    //   mapId: "mapbox.satellite",
    //   accessToken:"pk.eyJ1IjoieGNoYW9yIiwiYSI6ImNrdm0wZGlrcjZqM2EzMXExZXNsdno5eTEifQ.icTNYuBUhgW7Tt7zdNEToA",
    // }),
    //
    // imageryProvider: new Cesium.WebMapServiceImageryProvider({
    //   url : GeoServer.ntGeoWmsUrl,
    //   layers : GeoServer.layersName.layersNameBuilding,
    //   parameters: {
    //     service : 'WMS',
    //     format: 'image/png',
    //     transparent: true,
    //   }
    // }),
    contextOptions: {
      webgl: {
        alpha: true,
        depth: false,
        stencil: true,
        antialias: true,
        premultipliedAlpha: true,
        preserveDrawingBuffer: true,
        failIfMajorPerformanceCaveat: true,
      },
      allowTextureFilterAnisotropic: true,
    },
    // 天空盒
    skyBox: new Cesium.SkyBox({
      sources: {
        positiveX: require('@/assets/skybox/tycho2t3_80_px.jpg'),
        negativeX: require('@/assets/skybox/tycho2t3_80_mx.jpg'),
        positiveY: require('@/assets/skybox/tycho2t3_80_py.jpg'),
        negativeY: require('@/assets/skybox/tycho2t3_80_my.jpg'),
        positiveZ: require('@/assets/skybox/tycho2t3_80_pz.jpg'),
        negativeZ: require('@/assets/skybox/tycho2t3_80_mz.jpg'),
      },
    }),
  })
  //
  // viewer.clock.onTick.addEventListener(function () {
  //   if(viewer.camera.pitch > -3)   //角度可以定义，正数是朝上看，负数是朝下看
  //   {
  //     viewer.scene.screenSpaceCameraController.enableTilt = false;   //设置false为不允许相机倾斜
  //   }
  // });
  //
  // var mousePosition,startMousePosition;
  // var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
  // handler.setInputAction(function(movement) {
  //   mousePosition=startMousePosition= Cesium.Cartesian3.clone(movement.position);
  //   handler.setInputAction(function(movement) {
  //     mousePosition = movement.endPosition;
  //     var y = mousePosition.y - startMousePosition.y;
  //     if(y>0){
  //       viewer.scene.screenSpaceCameraController.enableTilt = true;        //鼠标从上往下划的时候允许倾斜相机
  //     }
  //   }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  // }, Cesium.ScreenSpaceEventType.MIDDLE_DOWN);
  //添加指南针
  viewer.scene.screenSpaceCameraController.minimumZoomDistance = 30;

  // viewer.scene.globe.show = false; //不显示地球，这条和地球透明度选一个就可以
  // 地球球体透明
  viewer.scene.globe.showGroundAtmosphere = false;
  viewer.scene.globe.baseColor = Cesium.Color.TRANSPARENT;
  viewer.scene.globe.translucency.enabled = true;
  viewer.scene.globe.undergroundColor = undefined;
  // viewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 0);
  // viewer.scene.backgroundcolor = new Cesium.Color(0, 0, 0, 0);
  // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 7000;
  return viewer;
}





export function addBorderWall(Cesium,viewer,points,height=200,bid='identify-area') {
  /**
   * @description: 添加园区动态光效墙
   * @param {*}
   * @author: citrusrlia@foxmail.com
   */
  let alp = 1,
      num = 0;

  let pointsarr = [];
  for(var i = 0;i<points.length;i++){
    let queryPoint = {};
    queryPoint.x = points[i][0];
    queryPoint.y = points[i][1];
    pointsarr[i] = queryPoint;
  }

  viewer.entities.remove(viewer.entities.getById(bid));
  var lonLatArrAall = getLonLatArrayWall(pointsarr,height);
  viewer.entities.add({
    id: bid,
    wall: {
      show: true,
      positions: new Cesium.Cartesian3.fromDegreesArrayHeights(lonLatArrAall),
      material: new Cesium.ImageMaterialProperty({
        image: '/img/fade_yellow.png',
        transparent: true,
        color: new Cesium.CallbackProperty(function () {
          if (num % 2 === 0) {
            alp -= 0.005
          } else {
            alp += 0.005
          }

          if (alp <= 0.3) {
            num++
          } else if (alp >= 1) {
            num++
          }
          return Cesium.Color.WHITE.withAlpha(alp)
        }, false),
      }),
    },
  })
}

export function getLonLatArrayWall(points,height=300) {
  var point3DWall = [];
  points.forEach(function (point) {
    point3DWall.push(point.x);
    point3DWall.push(point.y);
    point3DWall.push(height);
  });
  return point3DWall;
}

//三维添加对应地图
export function addLayersfor3d(Cesium,viewer,parmars){
  let layerProvier = new Cesium.WebMapServiceImageryProvider({
    url:parmars.url,
    layers:parmars.name,
    parameters:{
      transparent: true,
      format: "image/png",
      styles:parmars.styles ? parmars.styles : ''
    }
  })
  //添加图层方法
  let imageryProviderLayer = viewer.imageryLayers.addImageryProvider(layerProvier);
  //调整视角的方法
  // viewer.camera.setView({
  //   destination : Cesium.Cartesian3.fromDegrees(121.01578, 31.99425, 30000.0),
  //   orientation:{
  //     // 指向
  //     heading:Cesium.Math.toRadians(0,0),
  //     // 视角
  //     pitch :Cesium.Math.toRadians(-90) ,
  //     roll:0.0
  //   }
  // })
  return imageryProviderLayer
}

//图层数组进行初始化为ImageryProvider类型
export function initImageryProvider(Cesium,layerinfo) {
  return new Cesium.WebMapServiceImageryProvider({
      url:layerinfo.lurl,
      layers:layerinfo.lcode,
      parameters:{
        transparent: true,
        format: "image/png",
      }
  })
}
